package com.yao.yaoojbackendserviceclient.service;

import com.yao.yaoojbackendcommon.common.ErrorCode;
import com.yao.yaoojbackendcommon.exception.BusinessException;
import com.yao.yaoojbackendmodel.model.entity.User;
import com.yao.yaoojbackendmodel.model.enums.UserRoleEnum;
import com.yao.yaoojbackendmodel.model.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
//import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

import static com.yao.yaoojbackendcommon.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务
 */

@FeignClient(name = "yaooj-backend-user-service",path = "/api/user/inner")
//name:我要从Nacos注册中心去获取服务的名字  path:我们定义的全局前缀（去yml文件里面找）
public interface UserFeignClient {

    //userService.getById(userId)
    //userService.getUserVO(user)
    //userService.listByIds(userIdSet)
    //userService.isAdmin(loginUser)
    //userService.getLoginUser(request)

    /**
     * 根据id列表获取用户列表
     * @param idList
     * @return
     */
    @GetMapping("/get/ids")//需要远程调用的才打注解，不需要远程调用的不打注解
//    List<UserVO> listByIds(@RequestParam("idList") Collection<Long> idList);
    List<User> listByIds(@RequestParam("idList") Collection<Long> idList);

    /**
     * 根据id获取用户
     * @param userId
     * @return
     */
    @GetMapping("/get/id")
    User getById(@RequestParam("userId") long userId); //从请求的URL中提取参数值，并将其复制给方法参数
    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        //log.info("Session ID: {}, USER_LOGIN_STATE set: {}", request.getSession().getId(), user);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //可以考虑在这里做一些全局权限校验规则，通过JWT获取登录用户信息
        return currentUser;
    }

    default boolean isAdmin(User user){
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 获取脱敏的用户信息
     *
     * @param user
     * @return
     */
    default UserVO getUserVO(User user){
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}
